import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';

const serverUrl = 'https://localhost:1234';

function ChatRoom({ roomId }) {
  const [message, setMessage] = useState('');

  // 这是一个错误的例子,每次组件重新渲染(修改message)都会重新创建连接,导致之前的连接无法断开
  // 同时证明了lesson2的猜测,重新渲染后计算都会重新执行
  // 连接断开难道是组件卸载后清理依赖后触发?
  // const options = {
  //   serverUrl: serverUrl,
  //   roomId: roomId
  // };

  // useEffect(() => {
  //   const connection = createConnection(options);
  //   connection.connect();
  //   return () => connection.disconnect();
  // }, [options]);

  useEffect(() => {
    const options = {
      serverUrl: serverUrl,
      roomId: roomId
    };
    const connection = createConnection(options);
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]);

  return (
    <>
      <h1>欢迎来到 {roomId} 房间！</h1>
      <input value={message} onChange={e => setMessage(e.target.value)} />
    </>
  );
}

export default function App() {
  const [roomId, setRoomId] = useState('所有');
  return (
    <>
      <label>
        选择聊天室：{' '}
        <select
          value={roomId}
          onChange={e => setRoomId(e.target.value)}
        >
          <option value="general">general</option>
          <option value="travel">travel</option>
          <option value="music">music</option>
        </select>
      </label>
      <hr />
      <ChatRoom roomId={roomId} />
    </>
  );
}
